using System;

namespace Phoenix.Framework
{
    public class ControllerActionParameter
    {
        private ControllerActionParameter(object value)
            : this(null, value)
        { }

        internal ControllerActionParameter(string name, object value)
        {
            Name = name;
            Value = value;
        }

        public string Name { get; private set; }

        public object Value { get; private set; }

        public virtual bool IsMatch(Type parameterType)
        {
            return (Value == null && NullableType(parameterType)) || parameterType.IsInstanceOfType(Value);
        }

        static bool NullableType(Type parameterType)
        {
            return !parameterType.IsValueType ||
                (parameterType.IsGenericType && parameterType.GetGenericTypeDefinition() == typeof(Nullable<>));
        }

        internal static ControllerActionParameter FromObject(object obj)
        {
            var controllerActionParameter = obj as ControllerActionParameter;
            return controllerActionParameter ?? new ControllerActionParameter(obj);
        }
    }
}